<template>
  <div class="about">
     <!--搜索-->
        <el-row>
            <el-col :span="6"><el-input v-model="roleName" size="mini" placeholder="请输入角色名称"></el-input></el-col>
            <el-col :span="6"><el-input v-model="createBy" size="mini" placeholder="请输入添加人"></el-input></el-col>
            <el-col :span="6"><el-button type="primary" @click="search"  size="mini" icon="el-icon-search">搜索</el-button>
            &nbsp;<el-button type="primary"  size="mini" icon="el-icon-circle-plus" @click="handleAdd">添加</el-button></el-col>
            <el-col :span="6"><div class="grid-content bg-purple-light">&nbsp;</div></el-col>
        </el-row>
        <!--分页列表显示-->
        <el-row>
            <el-table
                    :data="tableData"
                    height="563"
                    style="width: 100%">
                <el-table-column
                        prop="roleName"
                        label="角色名称">
                </el-table-column>
                <!-- <el-table-column
                        prop="dataScope"
                        label="数据范围">
                </el-table-column> -->
                <el-table-column
                        prop="roleKey"
                        label="角色权限字符串">
                </el-table-column>
                <!-- <el-table-column
                        prop="roleSort"
                        label="显示顺序">
                </el-table-column> -->
                <el-table-column
                        prop="createBy"
                        label="添加人">
                </el-table-column>
                <el-table-column
                        prop="createTime"
                        label="添加时间">
                </el-table-column>
                <el-table-column
                        prop="updateBy"
                        label="修改人">
                </el-table-column>
                <el-table-column
                        prop="updateTime"
                        label="修改时间">
                </el-table-column>
                <el-table-column
                        prop="remark"
                        label="备注">
                </el-table-column>
                <el-table-column
                        prop="remark"
                        label="权限">
                    <template slot-scope="scope">
                        <el-button type="primary"  size="mini" width:10px icon="el-icon-circle-plus" @click="addMenus(scope.$index, scope.row)">授予权限</el-button>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="status"
                    label="状态">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.status"
                         @change='changeStatus($event,scope.row.status,scope.row.roleId)'
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        active-value="0"
                        inactive-value="1"
                        >
                    </el-switch>
                </template>
            </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <!--分页插件-->
        <el-row>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[2,3,5,10,100, 200, 300, 400]"
                    :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-row>
        <!--添加和更新 弹框-->
        <el-row>
            <el-dialog :title="title" :visible.sync="dialogFormVisible">
                <el-form :model="form">
                    <el-form-item label="角色名称" >
                        <el-input v-model="form.roleName" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="数据范围">
                        <el-input v-model="form.dataScope" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色权限字符串">
                        <el-input v-model="form.roleKey" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="显示顺序">
                        <el-input v-model="form.roleSort" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="添加人">
                        <el-input v-model="form.createBy" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="修改人">
                        <el-input v-model="form.updateBy" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="form.remark" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary"  size="mini" icon="el-icon-circle-plus" v-if="isShow" @click="addMenus(index,form)">授予权限</el-button>
                    </el-form-item>
                    <el-form-item label="是否启用">
                    <el-switch
                        v-model="form.status"
                         @change='changeStatus($event,form.status,form.roleId)'
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        active-value="0"
                        inactive-value="1"
                        >
                    </el-switch>
                </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addOrUpdate">确 定</el-button>
                </div>
            </el-dialog>
        </el-row>
        <!-- 资源框 -->
        <el-dialog title="菜单信息" :visible.sync="dialogMenuTreeVisible">
        <el-tree
            :data="data"
            :props="defaultProps"
            show-checkbox
            ref="tree"
            node-key="id"
            :default-checked-keys="checkedKeysMenus"
            check-strictly="true"
            highlight-current="true"
        ></el-tree>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogMenuTreeVisible = false">取 消</el-button>
            <el-button type="primary" @click="checkSelectNode">确 定</el-button>
        </div>
        </el-dialog>
  </div>
</template>
<script>
export default {
      data() {
        return {
               tableData:[],
                currentPage:1,//当前页面，默认1
                pageSize:2,//每页显示条数
                total:100,//分页总数量，默认值随便写，初始化时赋予新值
                roleName:'',//查询功能
                createBy:'',
                dialogFormVisible:false,
                title:'角色添加',
                form:{},
                dialogMenuTreeVisible: false,
                data: [], //树数据
                defaultProps: {
                children: "children",
                label: "label",
                },
                nowRoleId:'',
                checkedKeysMenus:[],  //选中的菜单
                // form:{
                //     roleId:1
                // },
                isShow:false
        }
      },
       created:function(){
               
               //初始化
                this.loadData();
            },
            methods:{
                //加载数据
                loadData(){
                   //动态菜单请求
                          this.$http.post("/api/cs/role/queryAll?pageNo="+this.currentPage+"&pageSize="+this.pageSize,{
                                            roleName:this.roleName,
                                            createBy:this.createBy
                                      }).then((response) => {
                                                 console.log(response);
                                              if(response.data.code==2000){
                                                  this.tableData = response.data.data.list;
                                                  this.total = response.data.data.total;
                                              }
                                })  
                        
                },
                //给角色添加权限
                checkSelectNode(){
                    let res = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());
                    console.log(res);
                    //  if(this.form.roleId==''||this.form.roleId==null){
                    //     this.checkedKeysMenus=res;
                    //     this.dialogMenuTreeVisible = false;
                    //     return;
                    // }
                    //定义一个json数据
                    var role={  
                        roleId:this.nowRoleId,
                    }
                    var _this = this;
                    
                    this.$http({
                        url:'/api/cs/role/update?menus='+res,
                        method:'post',
                        data:role,
                        header:{
                            'Content-Type':'application/json'  //如果写成contentType会报错
                        }
                    })
                        .then(function (response) {
                            console.log("=========");
                            console.log(response);
                            if(response.data.code==2000){
                                    //提示更新成功
                                _this.$message({
                                    //  message: '恭喜你，这是一条成功消息',
                                    message: response.data.message,
                                    type: 'success'
                                });
                                _this.dialogMenuTreeVisible = false;
                                console.log("授予权限成功");
                            }else{
                                 _this.$message.error(response.data.message);
                                console.log("授予权限失败");
                            }
                        })
                        .catch(function (error) {
                            _this.$message.error('系统出错了哦，请稍后再试。。。');
                            //失败处理
                            console.log(error);
                            console.log("==========");
                        });
                },


                //部门状态开关改变
                changeStatus($event,num,roleId){
                console.log(roleId);
                console.log($event);
                console.log(num);
                //定义一个json数据
                var jsons={  
                    roleId:roleId,
                    status:num
                }
                var _this = this;
                
                this.$http({
                    url:'/api/cs/role/update',
                    method:'post',
                    data:jsons,
                    header:{
                        'Content-Type':'application/json'  //如果写成contentType会报错
                    }
                })
                    .then(function (response) {
                        console.log("=========");
                        console.log(response);
                        if(response.data.code==2000){
                            console.log("角色状态改变成功");
                        }else{
                            console.log("角色状态改变失败");
                        }
                    })
                    .catch(function (error) {
                        //失败处理
                        console.log(error);
                        console.log("==========");
                    });
                },
                //授予权限
                addMenus(index, row){
                    //打开菜单弹框
                    this.dialogMenuTreeVisible = true;
                    //加载节点数据
                    this.loadTreeData();
                    //获取角色id
                    this.nowRoleId=row.roleId;
                    console.log("roleId====="+row.roleId);
                    //获取对应的菜单集合
                    this.loadMenuListByRoleId(row.roleId);
                    this.checkedKeysMenus=[];
                },
                //根据角色id获取菜单集合
                loadMenuListByRoleId(roleId){
                    var _this = this;
                    this.$http.get('/api/cs/roleMenu/queryMenuIdListByRoleId?roleId='+roleId)
                        .then(function (response) {
                            //正确请求时，回调函数
                            console.log("=========");
                            console.log(response);
                            if(response.data.code==2000){
                                console.log("menus========"+response.data.data);
                                _this.checkedKeysMenus = response.data.data;
                            }else{
                                console.log("==========");
                            }
                        })
                        .catch(function (error) {
                            //失败处理
                            console.log(error);
                            console.log("==========");
                        });
                },
                //加载节点数据
                loadTreeData() {
                var _this = this;
                //初始化数据
                this.$http
                    .get("/api/cs/menu/queryNodes")
                    .then(function (response) {
                        console.log("00000");
                    _this.data = response.data.data;
                    console.log("111111");
                    });
                },
                //各种绑定事件方法
                //每页数量发生变化
                handleSizeChange(val) {
                    console.log(`每页 ${val} 条`);
                    this.pageSize=val;
                    this.loadData();
                   /* axios.get('/dept/page',{
                        params: {
                            pageNo: this.currentPage,
                            pageSize: this.pageSize
                        }
                    })
                        .then(function (response) {
                            //正确请求时，回调函数
                            console.log(response);
                            if(response.data.code==2000){
                                _this.tableData = response.data.data.pageDept;
                                _this.total = response.data.data.total;
                            }
                        })
                        .catch(function (error) {
                            //失败处理
                            console.log(error);
                        });*/
                },
                //当前页发生变化
                handleCurrentChange(val) {
                    console.log(`当前页: ${val}`);
                    this.currentPage=val;
                    this.loadData();
                    /*axios.get('/dept/page',{
                        params: {
                            pageNo: this.currentPage,
                            pageSize:this.pageSize
                        }
                    })
                        .then(function (response) {
                            //正确请求时，回调函数
                            console.log(response);
                            if(response.data.code==2000){
                                _this.tableData = response.data.data.pageDept;
                                _this.total = response.data.data.total;
                            }
                        })
                        .catch(function (error) {
                            //失败处理
                            console.log(error);
                        });*/
                },
                //查询方法
                search(){
                   this.loadData();
                },
                //处理添加
                handleAdd(){
                    //清空原来form
                    this.form={};
                    //更新显示名称
                    this.title="角色添加";
                    //对话框显示
                    this.dialogFormVisible=true;
                    //清空菜单节点选中状态
                    this.checkedKeysMenus=[];
                },
                //处理编辑（弹出部门更新对话框）
                handleEdit(index, row) {
                    console.log(index, row);
                    //{deptNo:10,dname:'ACCOUNTING',loc:'纽约'}
                    // //清空菜单节点选中状态
                    // this.checkedKeysMenus=[];
                    this.form=row;
                    //更新显示名称
                    this.title="角色更新";
                    //对话框显示
                    this.dialogFormVisible=true;
                    
                },

                //提交表单数据（添加或者更新）
                addOrUpdate(){
                    let res = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());
                    console.log(res);
                    var  url ='/api/cs/role/update?menus='+res;
                    if(this.form.roleId==''||this.form.roleId==null){
                        url="/api/cs/role/insert?menus="+res;
                    }
                    var _this=this;
                    //提交方法
                    this.$http.post(url, this.form)
                        .then(function (response) {
                            console.log(response);
                            //提交成功
                            if(response.data.code==2000){
                                //关闭弹出框
                                _this.dialogFormVisible=false;
                                //提示更新成功
                                _this.$message({
                                  //  message: '恭喜你，这是一条成功消息',
                                    message: response.data.message,
                                    type: 'success'
                                });
                                //重新加载数据
                                _this.loadData();
                                //添加完成初始化
                                _this.form.roleId=1;
                            }else {
                                _this.$message.error(response.data.message);
                            }
                        })
                        .catch(function (error) {
                            _this.$message.error('错了哦，这是一条错误消息');
                        });
                },
                //处理删除（ 部门删除）
                handleDelete(index, row) {
                    console.log(index, row);
                   var _this=this;
                    //确认弹框
                    this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        //执行删除
                        this.$http.delete('/api/cs/role/deleteById?roleId='+row.roleId)
                            .then(function (response) {
                                //判断删除是否成功
                                 if(response.data.code==2000){
                                     //提示
                                     _this.$message({
                                         type: 'success',
                                         message: '删除成功!'
                                     });
                                     //重新加载数据
                                     _this.loadData();
                                 }else {
                                     _this.$message.error(response.data.message);
                                 }
                            })
                            .catch(function (error) {
                                //失败处理
                                console.log(error);
                                _this.$message.error('删除失败!');
                            });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });


                }
            }
    }
</script>
<style>

</style>
